<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="769px" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="auto" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_97')" prop="checkFuncId">
                            <el-select 
                                @change="checkFuncIdChange" 
                                filterable
                                v-model="ruleForm.checkFuncId" 
                                :placeholder="$t('key_98')"
                            >
                                <el-option
                                v-for="item in checkFuncIdOptions"
                                :key="item.id"
                                :label="item.checkFuncname"
                                :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_99')">
                            <el-popover
                                width="300"
                                trigger="click"
                                :visible="visible"
                                placement="bottom-end"
                            >   
                                <div class="popover-c">
                                    <span style="color:#04408c;margin-bottom:10px;display: block; width: 100%;font-weight: 600;">{{ $t('key_100') }}</span>
                                    <div>
                                        <el-input v-model="showData2" />
                                        <el-input style="margin: 10px 0" v-model="showName" />
                                    </div>
                                </div>
                                <div class="popover-r">
                                    <el-button size="small" @click="cancelClick">{{ $t('logOutCancel') }}</el-button>
                                    <el-button size="small" type="primary" @click="confirmClick">{{ $t('logOutConfirm') }}</el-button
                                    >
                                </div>
                                <template #reference>
                                    <el-input readonly @click="nameClick" v-model="ruleForm.name" clearable />
                                </template>
                            </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_101')">
                            <el-switch
                                v-model="ruleForm.disable"
                                class="ml-2"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_102')" prop="time_limit">
                            <el-input v-model="ruleForm.time_limit" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_22')">
                            <el-input type="textarea" v-model="ruleForm.description" :placeholder="$t('key_23')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-button style="margin-bottom: 10px;" @click="addClick" icon="ele-Plus" type="primary"> {{ $t('key_103') }} </el-button>
                        <el-table :data="ruleForm.checkerList" style="width: 100%">
                            <el-table-column :label="$t('key_104')" align="center">
                                <template #default="scope">
                                    <el-select 
                                        filterable
                                        v-model="scope.row.checkerID"
                                        :placeholder="$t('key_105')"
                                        @change="checkerChange(scope.row)"
                                    >
                                        <el-option
                                            v-for="item in checkerIDOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.jobNum"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('key_106')" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.lvl1" :placeholder="$t('key_107')" clearable />
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('key_108')" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.lvl2" :placeholder="$t('key_109')" clearable />
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('caoZuo')" align="center" >
                                <template #default="scope">
                                    <el-popconfirm
                                        confirm-button-text="确认"
                                        cancel-button-text="取消"
                                        icon="InfoFilled"
                                        icon-color="#626AEF"
                                        :title="$t('key_9')"
                                        @confirm="confirm(scope.row)"
                                    >
                                        <template #reference>
                                            <el-button class="icon-e" icon="ele-Delete" size="small" text type="danger"> {{ $t('key_10') }} </el-button>
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">{{ $t('key_24') }}</el-button>
                <el-button type="primary" :disabled="repeatDis" @click="submitForm(ruleFormRef)">{{ $t('key_25') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue'
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus'
import { sysCheckflowGetFlowSelector,sysUserSelector,sysCheckfuncGetFuncSelector,sysCheckflowAdd,sysCheckflowEdit } from '/@/api/manage/manage'
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id: any, // 组件id
    name: String, // 审核流程名称
    checkFuncId: String, // 审核功能
    time_limit: Number, // 有效时间
    disable: Boolean,
    description: String,
    checkerList: any,
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref()
        const ruleFormRef = ref()
        const nameOptions = ref()
        const checkFuncIdOptions = ref()
        const checkerIDOptions = ref()
        const visible = ref(false)
        const showData1 = ref() // 用于提交
        const showData2 = ref() // 用于显示
        const showName = ref() // 用于name显示
        let needName = ''

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** cancelClick 气泡取消 */
        const cancelClick = () => {
            visible.value = false
        }

        /*** confirmClick 气泡确认 */
        const confirmClick = () => {
            visible.value = false
            showData1.value = showData2.value
            state.ruleForm.name = showName.value
        }

        /*** nameClick 审核流程名称 */
        const nameClick = () => {
            if(needName === ''){
                ElMessage({
                    message: $t('key_110'),
                    type: 'warning',
                    duration:1000,
                })
            }else{
               visible.value = true 
            }
        }

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            name: [
				{ required: true, message: $t('key_111'), trigger: 'change' },
			],
            checkFuncId: [
				{ required: true, message: $t('key_112'), trigger: 'change' },
			],
            time_limit: [
				{ required: true, message: $t('key_113'), trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            visible.value = false 
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            visible.value = false
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if(valid){
                    let setObj = toRaw(state.ruleForm)
                    let len = setObj.checkerList.length
                    if(setObj.checkerList[len - 1].checkerID === ''){
                        ElMessage({
                            message: $t('key_114') + len + $t('key_115'),
                            type: 'warning',
                            duration: 1500,
                        })
                        return
                    }
                    let setArr:any[] = []
                    setObj.checkerList.map((i:any) => {
                        let setObj = {
                            checkerID: i.checkerID,
                            lvl1: Number(i.lvl1),
                            lvl2: Number(i.lvl2),
                        }
                        setArr.push(setObj)
                    })
                    setObj.checkerList = setArr
                    setObj.name = showData1.value + showName.value
                    if(setObj.id === ''){
                        const {id , ...param} = setObj
                        // console.log(param,'param')
                        let res:any = await sysCheckflowAdd(param)
                        if(res.success){
                            state.repeatDis = true
                            visible.value = false
                            ctx.emit('controlUseClick')
                            ctx.emit('updateData')
                        }else{
                            visible.value = false
                            ctx.emit('controlUseClick')
                        }
                    }else{
                        // console.log(setObj,'setObj')
                        let res:any = await sysCheckflowEdit(setObj)
                        if(res.success){
                            visible.value = false
                            state.repeatDis = true
                            ctx.emit('controlUseClick')
                            ctx.emit('updateData')
                        }else{
                            visible.value = false
                            ctx.emit('controlUseClick')
                        }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        let isAllowNum = 1
        let addNum = 1
        const addClick = () => {
            isAllowNum = isAllowNum += 1
            if(isAllowNum > 1){
                // console.log(state.ruleForm.checkerList[addNum - 1].checkerID,'checkerID')
                if(state.ruleForm.checkerList[addNum - 1].checkerID === ''){
                    ElMessage({
                        message: $t('key_116'),
                        type: 'warning',
                        duration: 1000,
                    })
                    return
                }
            }
            addNum = addNum += 1
            let personObj = {
                addNum : addNum, // 自增主键
                checkerID: '',
                // lvl1: addNum,
                // lvl2: addNum,
                lvl1: 0,
                lvl2: 0,
            }
            state.ruleForm.checkerList.push(personObj)
            // console.log(state.ruleForm.checkerList,'checkerList新增')
        }

        /*** confirm 移除 */
        const confirm = (t:any) => {
            if(state.ruleForm.checkerList.length === 1){
                ElMessage({
                    message: $t('key_117'),
                    type: 'error',
                    duration: 1000,
                })
                return
            }else{
                state.ruleForm.checkerList = state.ruleForm.checkerList.filter((i:any) => {
                    return i.addNum !== t.addNum
                })
                state.ruleForm.checkerList.map((m:any,i:any) => {
                    m.addNum = i + 1
                    // m.lvl1 = i + 1
                    // m.lvl2 = i + 1
                })
                addNum = state.ruleForm.checkerList.length
            }
            // console.log(state.ruleForm.checkerList,'checkerList移除')
            let needInfo = ''
            state.ruleForm.checkerList.map((i:any) => {
                needInfo += (i.checkerName + $t('key_118'))
            })
            state.ruleForm.name = delStrFun(needInfo,$t('key_119'))
            showName.value = delStrFun(needInfo,$t('key_120'))
        }

        /*** GetData 获取需要的数据 */
        const GetData = async () => {
            // 用户
            try {
                let res:any = await sysUserSelector()
                if(res.success){
                    checkerIDOptions.value = res.data
                }
            } catch (err) { return }

            // 审核流程
            try {
                let res:any = await sysCheckflowGetFlowSelector()
                if(res.success){
                    nameOptions.value = res.data
                }
            } catch (err) { return }

            // 审核功能
            try {
                let res:any = await sysCheckfuncGetFuncSelector()
                if(res.success){
                    checkFuncIdOptions.value = res.data
                }
            } catch (err) { return }
        }

        /*** delStrFun 删除指定位置字符 */
        const delStrFun = (str:any,n:any) => {
            str = [...str]
            let idx = str.lastIndexOf(n)
            str.splice(idx , 1)
            return str.join('')
        }

        /*** checkerChange 审核人改变事件 */
        const checkerChange = (val:any) => {
            let obj = checkerIDOptions.value.find((i:any) => {
                return i.jobNum === toRaw(val).checkerID
            })
            // console.log(obj,'obj')
            toRaw(val).checkerName = toRaw(obj).name
            let needInfo = ''
            state.ruleForm.checkerList.map((i:any) => {
                needInfo += (i.checkerName + $t('key_121'))
            })
            state.ruleForm.name = delStrFun(needInfo,$t('key_122'))
            showName.value = delStrFun(needInfo,$t('key_123'))
        }

        /*** checkFuncIdChange 审核功能下拉选择 */
        const checkFuncIdChange = (val:any) => {
            // console.log(val,'val')
            let obj = checkFuncIdOptions.value.find((i:any) => {
                return i.id === val
            })
            needName = toRaw(obj).checkFuncname
            showData1.value = toRaw(obj).checkFuncname + $t('key_124')
            showData2.value = toRaw(obj).checkFuncname + $t('key_125')
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                GetData()
                state.repeatDis = false
                if(props.repairInfo !== ''){
                    titleCon.value = $t('key_8')
                    let needData = JSON.parse(props.repairInfo)
                    let needInfo = ''

                    isAllowNum = needData.checkerList.length
                    addNum = needData.checkerList.length
                    needName = needData.checkFuncname

                    state.ruleForm.id = needData.id
                    state.ruleForm.checkFuncId = needData.checkFuncId
                    state.ruleForm.time_limit = needData.time_limit
                    state.ruleForm.disable = needData.disable
                    state.ruleForm.description = needData.description
                    if(needData.checkerList.length !== 0){
                        console.log(needData.checkerList,'checkerList')
                        needData.checkerList.map((i:any,t:any) => {
                            i.checkerID = Number(i.checkerID)
                            i.addNum = t + 1
                            needInfo += (i.checkerName + $t('key_126'))
                        })
                    }
                    state.ruleForm.name = delStrFun(needInfo,$t('key_127'))
                    showName.value = delStrFun(needInfo,$t('key_128'))
                    state.ruleForm.checkerList = needData.checkerList
                    if(JSON.parse(props.repairInfo).name.indexOf($t('key_129')) === -1){
                        showData1.value = JSON.parse(props.repairInfo).name
                        showData2.value = JSON.parse(props.repairInfo).name
                    }else{
                        showData1.value = JSON.parse(props.repairInfo).name.split($t('key_130'))[0] + $t('key_131')
                        showData2.value = JSON.parse(props.repairInfo).name.split($t('key_132'))[0] + $t('key_133')
                    }
                    // console.log(needData,'needData')
                }else{
                    showData1.value = ''
                    showData2.value = ''
                    titleCon.value = $t('xinZeng')
                    isAllowNum = 1
                    addNum = 1
                    needName = ''
                    state.ruleForm.id = ''
                    state.ruleForm.name = ''
                    showName.value = ''
                    state.ruleForm.checkFuncId = ''
                    state.ruleForm.time_limit = 24
                    state.ruleForm.disable = false
                    state.ruleForm.description = ''
                    state.ruleForm.checkerList = [
                        {
                            checkerID: '',
                            lvl1: 0,
                            lvl2: 0,
                        }
                    ]
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            confirm,
            addClick,
            nameOptions,
            checkFuncIdOptions,
            checkerIDOptions,
            checkerChange,
            checkFuncIdChange,
            cancelClick,
            confirmClick,
            visible,
            showData1,
            showData2,
            showName,
            nameClick,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%;
    }
    .popover-r{
        text-align: right; 
        margin: 0; 
        border-top:1px dashed #7fa8ec;
        padding-top: 10px;
    }
</style>